package cn.zqy.demo3.day01.Jdbc;

import cn.zqy.demo3.day01.Utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class Demo09JdbcLoginPrepared {
    public static void main(String[] args) {
        //1.键盘录入，接受用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("输入用户名：");
        String name = sc.next();
        System.out.println("输入密码：");
        String pass = sc.next();
        //2.调用方法
        boolean lo = new Demo09JdbcLoginPrepared().login(name, pass);
        //3.判断结果
        System.out.println(lo);
    }

    /**
     * 登录方法
     */
    public boolean login(String name, String password) {
        if (name == null || password == null) {
            return false;
        }
        //连接数据库判断是否登录成功
        Connection con = null;
        PreparedStatement sta = null;
        ResultSet rs = null;
        try{
            //1.获取连接
            con = JDBCUtils.getConnection();
            //2.定义sql
            String sql = "select * from users where name = ? and password = ?";
            //3.获取执行sql的对象
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, name);
            ps.setString(2, password);


            //4.执行查询
            rs = ps.executeQuery();
            return rs.next();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs, con, sta);
        }

        return false;  // 此处需要返回语句
    }
}
